package com.fasteat.mall.quartz;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * 任务管理
 */
@Component
public class QuartzManager {

	@Autowired
	@Qualifier("myScheduler")
	private Scheduler scheduler;

	@Autowired
	private TaskContainer container;

	/**
	 * 添加任务到定时器
	 *
	 * @param rule
	 */
	public void add(Rule rule) {
		try {
			// 定义任务，创建JobDetail实例，用于绑定Job实现类
			JobDetail jobDetail = JobBuilder.newJob(rule.getJobClass()).withIdentity(rule.getJobName(), rule.getJobGroupName()).build();
			// 定义触发器，采用cronTrigger规则
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(rule.getJobName(), rule.getJobGroupName())
					.startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
					.withSchedule(CronScheduleBuilder.cronSchedule(rule.getCronExpression())).startNow().build();
			// 将任务和触发器放到任务调度中
			scheduler.scheduleJob(jobDetail, trigger);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 启动时，将容器里到所有任务添加到定时器
	 */
	public void statup() {
		container.getContainer().forEach(task -> add(task));
	}

}
